package com.ffcs.web.services;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ffcs.web.daos.implementations.CounselorDao;
import com.ffcs.web.daos.implementations.OrderDao;
import com.ffcs.web.daos.implementations.StudyDao;
import com.ffcs.web.model.entity.Counselor;
import com.ffcs.web.model.entity.Order;
import com.ffcs.web.model.entity.Study;
import com.ffcs.web.model.requests.StudyRequest;
import com.ffcs.web.utils.ChinaeseUtil;
import com.ffcs.web.utils.CommonConfig;

@Service
public class StudyService {

	@Autowired
	private StudyDao studyDao;
	@Autowired
	private CounselorDao counselorDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private OrderDao orderDao;

	public Study getStudyDesc(String id) {
		Study study=studyDao.get(Integer.parseInt(id));
		return study;
	}

	public List<Study> getStudyList(StudyRequest studyRequest) {
		
		StringBuilder sql=new StringBuilder("select * from wechat_study t where studyStatus=1");
		sql.append(" and startStudy>curdate()");
		if (StringUtils.isNotBlank(studyRequest.getStudyType())) {
			sql.append(" and studyType="+studyRequest.getStudyType());
		}
		
		if (StringUtils.isNotBlank(studyRequest.getCounseTel())) {
			sql.append(" and counseTel="+studyRequest.getCounseTel());
		}
		if (StringUtils.isNotBlank(studyRequest.getTxtsearch())) {
			String txtsearch=studyRequest.getTxtsearch();
			if(!ChinaeseUtil.isChineseChar(txtsearch)){
				try {
					txtsearch=new String(txtsearch.getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			sql.append(" and (studyTitle like '%"+txtsearch+"%' ");
			sql.append(" or counseName like '%"+txtsearch+"%' ");
			sql.append(" or studyLabel like '%"+txtsearch+"%' ");
			sql.append(" or studyContent like '%"+txtsearch+"%' ");
			sql.append(" )");
		}
		
		
		
		if (StringUtils.isNotBlank(studyRequest.getCityName())) {
			String cityName=studyRequest.getCityName();
			
			if(!ChinaeseUtil.isChineseChar(cityName)){
				try {
					cityName=new String(cityName.getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			sql.append(" and studyCity='"+cityName+"'");
		}
		if (StringUtils.isNotBlank(studyRequest.getOrderBy())) {
			
			if(studyRequest.getOrderBy().equals("1")){
				sql.append(" order by startStudy asc");
			}else if(studyRequest.getOrderBy().equals("2")){
				sql.append(" order by startStudy desc");
			}else if(studyRequest.getOrderBy().equals("3")){
				sql.append(" order by studyPrice asc");
			}else if(studyRequest.getOrderBy().equals("4")){
				sql.append(" order by studyPrice desc");
			}
		}else{
			sql.append(" order by sort asc");
		}
		
		System.out.println("培训库sql="+sql.toString());
		return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<Study>(Study.class));
	}

	@Transactional
	public void updateStudy(Integer studyId) {
		Study study=studyDao.get(studyId);
		study.setSignStudent(study.getSignStudent()+1);
		studyDao.save(study);
	}
	
	@Transactional
	public void updateJianStudy(Integer studyId) {
		Study study=studyDao.get(studyId);
		study.setSignStudent(study.getSignStudent()-1);
		studyDao.save(study);
	}

	public List<Study> getStudyList(String counseTel, String studyType) {
		StringBuilder sql=new StringBuilder("select * from wechat_study t where 1=1");
		sql.append(" and studyType="+studyType);
		sql.append(" and counseTel="+counseTel);
		sql.append(" order by startStudy desc");
		System.out.println("培训库sql="+sql.toString());
		return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<Study>(Study.class));
	}

	/**
	 * 新增培训
	 * @param counseTel
	 * @param studyTitle
	 * @param studyDirection
	 * @param maxStudent
	 * @param startStudy
	 * @param endStudy
	 * @param studyPrice
	 * @param studyLabel
	 * @param studyContent
	 * @param studyUrl
	 * @throws ParseException
	 */
	@Transactional
	public void addPeixun(String studyCity,String counseTel,String studyTitle, String studyDirection,
			String maxStudent, String startStudy, String endStudy,
			String studyPrice, String studyLabel, String studyContent,
			String studyUrl,String studyUrl2,String studyUrl3,String studyType,String flag) throws ParseException {
		Study study=new Study();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		study.setEndStudy(sdf.parse(endStudy));
		study.setStartStudy(sdf.parse(startStudy));
		study.setMaxStudent(Integer.parseInt(maxStudent));
		study.setSignStudent(0);
		Counselor counselor=counselorDao.findUniqueByPropertyName("counseTel",counseTel);
		study.setStudyCity(ChinaeseUtil.CharTOChinaese(studyCity));
		study.setCounseName(counselor.getCounseName());
		study.setCounseTel(counseTel);
		
		/**
		 * <img alt="" src="http://c.hiphotos.baidu.com/exp/w=500/sign=873c1335133853438ccf8721a
		 * 313b01f/8435e5dde71190efc4d07286cd1b9d16fdfa6044.jpg" style="width: 500px; height: 300px;" />
		 */
		String picUrlFront=CommonConfig.getProperty("PIC_URL_FRONT");
		String styContent=ChinaeseUtil.CharTOChinaese(studyContent);
		styContent+="<img src='"+picUrlFront+studyUrl+"' style='width: 100%; height: 100%;'/>";
		if(!studyUrl2.equals("")){
			styContent+="<img src='"+picUrlFront+studyUrl2+"' style='width: 100%; height: 100%;'/>";
		}
		if(!studyUrl3.equals("")){
			styContent+="<img src='"+picUrlFront+studyUrl3+"' style='width: 100%; height: 100%;'/>";
		}
		study.setStudyContent(styContent);
		study.setStudyDirection(studyDirection);
		study.setStudyLabel(ChinaeseUtil.CharTOChinaese(studyLabel));
		study.setStudyPrice(Double.parseDouble(studyPrice));
		study.setStudyStatus("2");
		study.setStudyTitle(ChinaeseUtil.CharTOChinaese(studyTitle));
		study.setStudyType(studyType);
		study.setStudyUrl(studyUrl);
		study.setIsBanner((short)0);
		study.setSort(new Date().getTime());
		study.setPublisher(counselor.getCounseName());
		study.setCreateTime(new Date());
		studyDao.save(study);
	}
	
	/**
	 * 修改培训信息
	 * @param counseTel
	 * @param studyTitle
	 * @param studyDirection
	 * @param maxStudent
	 * @param startStudy
	 * @param endStudy
	 * @param studyPrice
	 * @param studyLabel
	 * @param studyContent
	 * @param studyUrl
	 * @throws ParseException
	 */
	@Transactional
	public void addPeixun(String id,String counseTel,String studyTitle, String studyDirection,
			String maxStudent, String startStudy, String endStudy,
			String studyPrice, String studyLabel, String studyContent,
			String studyUrl) throws ParseException {
		Study study=studyDao.get(Integer.parseInt(id));
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		study.setEndStudy(sdf.parse(endStudy));
		study.setStartStudy(sdf.parse(startStudy));
		study.setMaxStudent(Integer.parseInt(maxStudent));
		study.setSignStudent(0);
		
		study.setStudyContent(ChinaeseUtil.CharTOChinaese(studyContent));
		study.setStudyDirection(studyDirection);
		study.setStudyLabel(ChinaeseUtil.CharTOChinaese(studyLabel));
		study.setStudyPrice(Double.parseDouble(studyPrice));
		study.setStudyStatus("1");
		study.setStudyTitle(ChinaeseUtil.CharTOChinaese(studyTitle));
		study.setStudyType("2");
		if(!studyUrl.equals("")){
			study.setStudyUrl(studyUrl);
		}
		studyDao.save(study);
	}

	@Transactional
	public void deleteStudy(String studyId) {
		Study study=studyDao.get(Integer.parseInt(studyId));
		studyDao.remove(study);
	}

	public String isHuifuPeixun(Integer id, String studyId) {
		Order orderExample=new Order();
		orderExample.setUserId(id);
		orderExample.setStudyId(Integer.parseInt(studyId));
		List<Order> orderList=orderDao.findByExample(orderExample);
		if(orderList.size()>0){
			if("".equals(orderList.get(0).getPingjia()) || null==orderList.get(0).getPingjia()){
				return "0"+","+orderList.get(0).getOrderSn();
			}else{
				return "1";
			}
		}else{
			return "2";
		}
	}
}
